<template>
  <!-- 群设置界面 -->
  <div class="group-container">
    <div class="backbar fix-bar">
      <div class="back flex-center" v-hammer:tap="(ev) => $router.push({name: 'ChatPanel'})">
        <i class="fa fa-angle-left fa-lgl"></i>
        <span>返回</span>
      </div>
    </div>

    <div class="member-list">
      <!-- 群成员列表 -->
      <!-- <router-link to="/Sub/GroupMembers" class="title"> -->
      <div class="title">
        <div>成员列表</div>
        <div>
          <span>共 {{ groupMembers.length }} 人</span>
          <span>
            <i class="fa fa-angle-right"></i>
          </span>
        </div>
      </div>
      <!-- </router-link> -->

      <div class="list-wrapper">
        <ul>
          <li @click="onMemberClicked(item, i)" v-for="(item, i) of groupMembers" :key="i">
            <img :src="item.headUrl" alt class="head-url" />
            <div class="username ellipsis">{{ item.nickname }}</div>
          </li>
          <!-- <li class="add-member" @click="onAddMember">

          </li>-->
          <li
            class="delete-member"
            @click="onDeleteMember"
            v-if="isAdmin && groupMembers.length > 1"
          >
            <div class="image-wrapper flex-center">
              <img src="@/assets/icons/minus.svg" alt />
            </div>
          </li>
        </ul>
      </div>
    </div>

    <div class="section-wrapper" v-if="isAdmin">
      <router-link tag="div" class="list-item" to="/Sub/ApplyList">
        <div>申请列表</div>
        <div>
          <i class="fa fa-angle-right"></i>
        </div>
      </router-link>

      <router-link tag="div" class="list-item" to="/Sub/QuitList" v-if="isOwner">
        <div>退群列表</div>
        <div>
          <i class="fa fa-angle-right"></i>
        </div>
      </router-link>
    </div>

    <div class="section-wrapper">
      <div class="list-item" @click="onGotoRoute('GroupName', '只有群主可修改群名称')">
        <div>群名称</div>
        <div class="flexbox justify-between">
          <div class="group-nick ellipsis">{{ groupSetting.info.groupNick }}</div>
          <i class="fa fa-angle-right"></i>
        </div>
      </div>
      <!-- v-if="isAdmin" -->
      <div class="list-item" @click="onGotoRoute('GroupBonus', '只有群主可修改群积分')" v-if="isAdmin">
        <div>群积分</div>
        <div>
          <i class="fa fa-angle-right"></i>
        </div>
      </div>

      <!-- <div class="list-item" @click="$router.push({name: 'GroupNotice'})">
        <div>群公告</div>
        <div>
          <i class="fa fa-angle-right"></i>
        </div>
      </div>-->

      <router-link tag="div" class="list-item" to="/Sub/GroupQrcode">
        <div>群号和二维码</div>
        <div>
          <i class="fa qrcode"></i>
          <i class="fa fa-angle-right"></i>
        </div>
      </router-link>

      <router-link tag="div" class="list-item" to="/Sub/GroupManage" v-if="isOwner">
        <div>群管理</div>
        <div>
          <i class="fa qrcode"></i>
          <i class="fa fa-angle-right"></i>
        </div>
      </router-link>
    </div>

    <div class="section-wrapper">
      <div class="list-item">
        <div>入群认证</div>
        <div>
          <cube-switch
            v-hammer:tap="(ev) => onSettingChange(ev, 1)"
            :disabled="allowApply"
            v-model="applyJoinType"
          ></cube-switch>
        </div>
      </div>

      <div class="list-item">
        <div>置顶聊天</div>
        <div>
          <cube-switch v-hammer:tap="(ev) => onSettingChange(ev, 2)" v-model="isTop"></cube-switch>
        </div>
      </div>

      <div class="list-item">
        <div>全员禁言</div>
        <div>
          <cube-switch v-hammer:tap="onShutupChange" :disabled="allowShutup" v-model="isShutup"></cube-switch>
        </div>
      </div>
    </div>

    <div class="section-wrapper">
      <div class="list-item flex-center" @click="onQuitGroup">
        <div class="quit-group">删除并退出</div>
      </div>
    </div>

    <delete-member
      @hide="showDeleteMember = false"
      class="add-group-wrapper"

      :class="{'show':showDeleteMember }"
      v-if="showDeleteMember"
    />
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { RawLocation } from "vue-router";
import { DIALOGUE, ImClient, MsgTypeKV } from "@/api/socket/imClient";
import {
  Msg,
  Session,
  Webim,
  Text,
  Face,
  Images,
  GroupTip,
  Sound,
  Custom
} from "@/utils/types";
import { Action, Mutation, Getter, namespace } from "vuex-class";
import { Response } from "@/api/bean";
import MessageMixin from "@/mixins";
import { JoinType } from '@/utils/constants';
declare const webim: Webim;
declare const $Vue: Vue;
const userModule = namespace("userModule");
const chatModule = namespace("chatModule");

@Component<GroupSetting>({
  mixins: [MessageMixin]
})
export default class GroupSetting extends Vue {
  @userModule.State("selToID") selToID: any;
  @userModule.State("selSess") selSess: any;
  @userModule.State("selType") selType: any;
  @userModule.State("loginInfo") loginInfo: any;
  @userModule.State("friendHeadUrl") friendHeadUrl: any;
  @userModule.State("memberInfo") memberInfo: any;
  @userModule.State("groupMembers") groupMembers: any;
  @userModule.Action("saveSelSessFN") saveSelSessFN: any;
  @userModule.Action("saveGroupMembersFN") saveGroupMembersFN: any;
  @userModule.Action("saveMemberInfoFN") saveMemberInfoFN: any;

  @chatModule.State("groupSetting") groupSetting: any;
  @chatModule.Action("saveGroupSettingFN") saveGroupSettingFN: any;

  private status: boolean = true;

  private memberList: Array<any> = [
    // {
    //   headUrl: 'http://b-ssl.duitang.com/uploads/item/201805/13/20180513224039_tgfwu.png',
    //   username: '比好'
    // },
  ];

  // 申请 和 禁言 群主才可用
  private allowApply: boolean = false;
  private allowShutup: boolean = false;

  // 显示删除成员信息
  private showDeleteMember: boolean = false;

  // 是否为管理员
  private isAdmin: boolean = false;
  // 是否为群主
  private isOwner: boolean = false;

  private memberCount: number = 0;

  private setting: any = {
    applyJoinType: false,
    isShutup: false,
    isTop: false,
  };


  private get applyJoinType() {
    // if (this.groupSetting.info.applyJoinType === 2) {
    //   return true
    // } else if (this.groupSetting.info.applyJoinType === 1) {
    //   return false;
    // }
    return this.groupSetting.info.applyJoinType === 2;
  }

  private set applyJoinType(value) {

  }

  private get isTop() {
    return Boolean(this.groupSetting.isTop)
  }
  private set isTop(value) {

  }
  private get isShutup() {
    return Boolean(this.groupSetting.info.isShutup)
  }
  private set isShutup(value) {

  }
  private eventList: Array<string> = [
    "$getGroupInfoByGroupId",
    "$getMemberList",
    "$quitGroup",
    "$updateGroupSetting",
    "$switchShutup",
    "$kickOut",
    "$shutUpOn",
  ];

  /**
   * 生命周期函数
   */
  protected mounted() {
    this.initEvents(this.eventList);
    this.memberList = this.groupMembers.slice();

    if (!this.groupSetting.status) {
      this.$router.push({
        name: 'Chat',
      })
    }

    this.sendMessage(MsgTypeKV.getMemberList, {
      groupId: sessionStorage.getItem("groupId")
    });

    // this.sendMessage(MsgTypeKV.getGroupInfoByGroupId, {
    //   groupId: sessionStorage.getItem("groupId")
    // });

    this.isAdmin = this.groupSetting.status === 1 || this.groupSetting.status === 2;

    this.isOwner = this.groupSetting.status === 1;

    this.allowApply = this.allowShutup = !(
      this.groupSetting.status === 1
    );
  }

  /**
   * 退出群聊
   */
  private onQuitGroup() {
    this.$createDialog({
      type: 'confirm',
      icon: 'cubeic-alert',
      title: '确认退出群聊吗?',
      content: '',
      confirmBtn: {
        text: '确定',
        active: true,
        disabled: false,
        href: 'javascript:;'
      },
      cancelBtn: {
        text: '取消',
        active: false,
        disabled: false,
        href: 'javascript:;'
      },
      onConfirm: () => {
        this.sendMessage(MsgTypeKV.quitGroup);
      },
      onCancel: () => {

      }
    }).show()
  }

  /**
   * 添加群成员
   */
  private onAddMember() {

  }

  /**
   * 删除群成员
   */
  private onDeleteMember() {
    this.showDeleteMember = true;
  }

  /**
   * 修改用户设置
   */
  private onSettingChange(ev: any, type: number) {

    let applyJoinType;
    // (2需要验证，1自由加入，3禁止加入)
    if (this.applyJoinType) {
      applyJoinType = JoinType.FreeJoin;
    } else {
      applyJoinType = JoinType.NeedPermission;
    }
    let info = Object.assign({}, this.groupSetting.info);

    let param: any = {
      info,
    }
    if (type === 1) {
      if (this.isOwner) {
        param.info.applyJoinType = applyJoinType;
      } else {
        return;
      }
    } else if (type === 2) {
      param.isTop = this.isTop ? 0 : 1;
    }

    this.sendMessage(MsgTypeKV.updateGroupSetting, param);
  }

  /**
   * 切换禁言
   */
  private onShutupChange() {
    if (this.isOwner) {
      this.sendMessage(MsgTypeKV.switchShutup, {
        info: this.groupSetting.info
      });
    }
  }

  /**
   * 修改群名称
   */
  private onGotoRoute(routeName: string, msg: string) {
    if (this.isOwner) {
      this.$router.push({
        name: routeName,
      });
    } else {
      this.$createToast({
        txt: msg,
        type: "warn",
        time: 3000
      }).show();
    }

  }
  /**
   * 修改群名称
   */
  private onMemberClicked(item, i) {
    this.saveMemberInfoFN({
      fromAccount: item.imAccount,
      nickname: item.nickname,
      userId: item.userId,
      headUrl: item.headUrl,
    });
    this.$router.push({
      name: 'MemberInfo',
    });
  }

  /**
 * 发送自定义的tip消息
 */
  private sendCustomTip(tip: any) {
    if (!this.selToID) {
      // selToID 为全局变量，表示当前正在进行的聊天 ID，当聊天类型为私聊时，该值为好友帐号，否则为群号。
      this.$createToast({
        txt: "您还没有选择群，暂不能聊天",
        type: "warn",
        time: 3000
      }).show();
      return;
    }

    let data = JSON.stringify(tip.content);
    let desc = "message-tip";
    let ext = tip.ext;
    let msgLen = webim.Tool.getStrBytes(data);
    if (data.length < 1) {
      return;
    }
    let maxLen, errInfo;
    if (this.selType == webim.SESSION_TYPE.C2C) {
      maxLen = webim.MSG_MAX_LENGTH.C2C;
      errInfo = "消息长度超出限制(最多" + Math.round(maxLen / 3) + "汉字)";
    } else {
      maxLen = webim.MSG_MAX_LENGTH.GROUP; // 八千字节
      errInfo = "消息长度超出限制(最多" + Math.round(maxLen / 3) + "汉字)";
    }
    if (msgLen > maxLen) {
      this.$createToast({
        txt: errInfo,
        type: "warn",
        time: 3000
      }).show();
      return;
    }
    let selSess = webim.MsgStore.sessByTypeId(
      webim.SESSION_TYPE.GROUP,
      this.selToID,
    );
    if (!selSess) {
      selSess = new webim.Session(
        this.selType,
        this.selToID,
        this.selToID,
        this.friendHeadUrl,
        Math.round(new Date().getTime())
      );
      this.saveSelSessFN(selSess);
    }

    let msg = new webim.Msg(
      selSess,
      true,
      -1,
      -1,
      -1,
      this.loginInfo.identifier,
      0,
      this.loginInfo.identifierNick
    );
    let customObj = new webim.Msg.Elem.Custom(data, desc, ext);
    msg.addCustom(customObj);
    //调用发送消息接口
    webim.sendMsg(
      msg,
      (resp) => { },
      (err) => {
        // this.$createToast({
        //   txt: err.ErrorInfo,
        //   type: "warn",
        //   time: 3000
        // }).show();
      }
    );

  }

  /**
   * 根据群号搜索群设置信息
   */
  private $getGroupInfoByGroupId(data: any) {
    if (data.result === 0) {
      // 是否置顶
      // this.setting.isTop = Boolean(data.isTop);
      // this.setting.isShutup = Boolean(data.info.isShutup);

      // let applyJoinType = data.info.applyJoinType;
      // if (applyJoinType === JoinType.FreeJoin) {
      //   this.setting.applyJoinType = false;
      // } else if (applyJoinType === JoinType.NeedPermission) {
      //   this.setting.applyJoinType = true;
      // }
      this.saveGroupSettingFN(data);
    } else {
      this.$createToast({
        txt: data.message,
        type: "warn",
        time: 3000
      }).show();
    }
  }

  /**
   * 获取群成员列表
   */
  private $getMemberList(data: any) {
    if (data.result === 0) {
      this.memberList = data.infoList;
      this.saveGroupMembersFN(data.infoList);
    } else {
      // this.$createToast({
      //   txt: data.message,
      //   type: "warn",
      //   time: 3000
      // }).show();
    }
  }

  /**
   * 用户退群
   */
  private $quitGroup(data: Response<any>) {
    if (data.result === 0) {
      this.$createToast({
        txt: data.message,
        type: "correct",
        time: 3000
      }).show();
      this.$router.push({
        name: 'Chat'
      });
    } else {
      this.$createToast({
        txt: data.message,
        type: "warn",
        time: 3000,
      }).show();
    }
  }

  /**
   * 更新群设置
   */
  private $updateGroupSetting(data: Response<any>) {
    if (data.result === 0) {
      this.$createToast({
        txt: data.message,
        type: "correct",
        time: 3000
      }).show();
      // 更新群设置
      this.sendMessage(MsgTypeKV.getGroupInfoByGroupId, {
        groupId: sessionStorage.getItem("groupId")
      });
    } else {
      // this.$createToast({
      //   txt: data.message,
      //   type: "warn",
      //   time: 3000
      // }).show();
    }
  }

  /**
   * 更新群设置
   */
  private $switchShutup(data: Response<any>) {
    if (data.result === 0) {
      // this.$createToast({
      //   txt: data.message,
      //   type: "correct",
      //   time: 3000
      // }).show();
      this.sendMessage(MsgTypeKV.getGroupInfoByGroupId, {
        groupId: sessionStorage.getItem("groupId")
      });
    } else {
      // this.$createToast({
      //   txt: data.message,
      //   type: "warn",
      //   time: 3000
      // }).show();
    }
  }

  /**
   * 踢人回调
   */
  private $kickOut(data: Response<any>) {
    if (data.result === 0) {
      this.$createToast({
        txt: data.message,
        type: "correct",
        time: 3000
      }).show();
      this.sendMessage(MsgTypeKV.getGroupInfoByGroupId, {
        groupId: sessionStorage.getItem("groupId")
      });
      this.sendMessage(MsgTypeKV.getMemberList, {
        groupId: sessionStorage.getItem("groupId")
      });
      this.showDeleteMember = false;
    } else {
      this.$createToast({
        txt: data.message,
        type: "warn",
        time: 3000
      }).show();
    }
  }

  /**
   * 开启群聊禁言
   */
  private $shutUpOn(data: any) {
    let content = {
      content: '开启了全员禁言'
    };
    let ext = {
      operatorId: data.operatorId,
      operatorName: data.operatorName,
    };

    this.sendMessage(MsgTypeKV.getGroupInfoByGroupId, {
      groupId: sessionStorage.getItem("groupId")
    });

    if (localStorage.getItem('userId') == data.operatorId) {
      this.sendCustomTip({
        content,
        ext: JSON.stringify(ext),
      });
    }
    // 如果是自己发送的 则发送消息到群中
  }

  /**
   * 关闭群聊禁言
   */
  private $shutUpOff(data: any) {
    let content = {
      content: '关闭了全员禁言'
    };
    let ext = {
      operatorId: data.operatorId,
      operatorName: data.operatorName,
    };
    this.isShutup = false;
    // 如果是自己发送的 则发送消息到群中
    if (localStorage.getItem('userId') == data.operatorId) {
      this.sendCustomTip({
        content,
        ext: JSON.stringify(ext),
      });
    }
  }

}
</script>

<style lang="stylus" scoped>
.group-container
  width 100%
  height 100%
  background #efefef
  padding-top 44px
  box-sizing border-box
  overflow-x hidden
  overflow-y auto
  // position fixed
  // top 0
  // left 0
  .member-list
    background white
    padding-bottom 16px
    flex-wrap wrap
    .title
      height 32px
      display flex
      justify-content space-between
      align-items center
      color #898989
      padding 4px 12px
      border-bottom 1px solid #f5f5f5

    .list-wrapper
      display flex 
      justify-content center
      ul
        width 100%
        display flex
        justify-content flex-start
        align-items flex-start
        flex-wrap wrap
        padding 8px 
        box-sizing border-box
        li 
          margin 9px
          margin-bottom 16px
          width 52px
          height 52px
          .head-url
            width 90%
            height 90%
            border-radius 4px
          .username 
            font-size 12px
            color #898989
            margin-top 2px
  .section-wrapper
    margin-top 6px
    .list-item 
      user-select none
      width 100% 
      height 48px 
      display flex
      justify-content space-between
      align-items center
      background white
      padding 2px 12px
      box-sizing border-box
      border-bottom 1px solid #f5f5f5

.quit-group
  color #f44336
  text-align center
  width 100%

.group-nick
  font-size 15px
  color #676767
  position relative
  width 100px

.delete-member
  .image-wrapper
    border-radius 4px
    border 1.5px solid #e2e2e2
    height 90%
    img
      width 50%

.fix-bar
  position fixed
  top 0
  left 0
</style>

